package com.zhonglz.commons.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zhonglz.util.jwt.JwtUtils;
import com.zhonglz.util.tools.ObjectUtils;

/**
 * 系统拦截器
 * @author zhonglz
 * 时间:2019年6月17日
 */
public class SystemInterceptor implements HandlerInterceptor {
	private static Logger logger = LoggerFactory.getLogger(SystemInterceptor.class);

	@Autowired
	private RedisTemplate redisTemplate;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception{
		String token = request.getHeader("Authorization");//获取请求头中token值
		logger.info("进入拦截器，请求token："+token);
		//获取token以后调用jwt工具类进行解码判断并且获取用户信息
		if(ObjectUtils.isNotEmpty(token)) {
			try {
				JwtUtils.verify(token);
			} catch (Exception e) {
				logger.info("token异常："+e.getMessage());
				logger.info("令牌失效或无效");
				request.getRequestDispatcher("/error/userError401").forward(request, response);
				//请求跳转值错误请求
				return false;
			}
		}else {
			request.getRequestDispatcher("/error/userError400").forward(request, response);
			//请求跳转值错误请求
			return false;
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
